% This code is based on demand_estimation_AK/consumer_v_ftn.m

function [v, c1_all] = predict_v(p1, p2_input, ...
    alpha,  Delta_xi,...
    N_y, resource_y1, resource_y2, pr_s_row, KM,...
    rho, crra, beta_c, U0_mm, B1_c, B2_c, T1, delta)

NN = size(p1,1); % major insurers + # fringes

v = zeros(N_y, NN); 
c1_all = zeros(N_y, NN);

% loop thru each insurer jj in the market
for jj=1:NN
    
    % 2nd period probability distribution 
    pr_s = pr_s_row'; % KM x 1

    % jj's prices
    p_jj1 = p1(jj);
    p_jj2 = p2_input(jj, :); 
    
    Delta_xi_jj = Delta_xi(jj);
    
    % first-period annual consumption (N_y x 1)
    c1 = resource_y1-p_jj1;
    
    % second-period annual consumption in each state k if not lapse (N_y x KM)
    c2 = repmat(resource_y2,1,KM)-repmat(p_jj2,N_y,1);

    % second-period utility in each state k if not lapse (N_y x KM)
    U_stay = B2_c*(alpha*u_c(c2,rho,crra) +  Delta_xi_jj);

    % second-period utility in each state k if lapse 
    U_lapse = U0_mm; % N_y x K
    U_lapse_mat = repmat(U_lapse, 1, 4); % N_y x KM

    % expected utility conditional on realized state 
    U = (1- unique(delta))*U_stay + unique(delta)*U_lapse_mat; % N_y x KM

    % expected 2nd-period utility (N_y x 1)
    EU = U*pr_s;
    
    % size(v_jj) = N_y x 1
    v_jj = B1_c*(alpha*u_c(c1,rho,crra) +  Delta_xi_jj) + (beta_c^T1)*EU;

    % set v_jj to -Inf if income less than p_jj in any state
    flag = [c1 c2];
    flag = (flag<0);
    flag = (sum(flag,2)>0);
    v_jj(flag==1)=-Inf;
    
    % save
    v(:,jj) = v_jj;
    c1_all(:,jj) = c1;
end


